import QtQuick 1.0
import "../WebAccess/TwitterAPI.js" as TwitterAPI
import "../Util/Util.js" as Util


ModelXmlList {
//    id: _root

    property bool isFirst: true         //最初に1回だけ処理する内容の為のフラグ

    property bool accessReady: true     //上位で読込みに関するReady状態を指定する
    property bool isReady: ready && accessReady    //状態の合成（最終的にこれを見る）

    property bool ready: status == XmlListModel.Ready
    property int pageNumber: 1

    property int sourceType: 0              //取得するデータの種類    0:timeline 1:mention
    property string sourceTimeline: ""      //Timeline用

    property string listId: ""              //リストのTLを表示する時のID
    property string listIdPrev: ""    //前回表示してたlistのID

    property string queryParam1: "user"     //ユーザー情報系のディレクトリ（通常TLとDMを切り替える）

    //xmlの解析関係
    query: makeQuery();//"/statuses/status"
    XmlRole { name: "_status_id"; query: "id/string()"; isKey: true}
    XmlRole { name: "_name"; query: queryParam1 + "/name/string()"; }
    XmlRole { name: "_screen_name"; query: queryParam1 + "/screen_name/string()"; }
    XmlRole { name: "_text"; query: "text/string()"; }
    XmlRole { name: "_icon"; query: queryParam1 + "/profile_image_url/string()";}
    XmlRole { name: "_date"; query: "created_at/string()"; }
    XmlRole { name: "_in_reply_to_status_id"; query: "in_reply_to_status_id/string()"; }
    XmlRole { name: "_in_reply_to_screen_name"; query: "in_reply_to_screen_name/string()"; }
    XmlRole { name: "_source"; query: "source/string()"; }
    XmlRole { name: "_favorited"; query: "favorited/string()"; }

    XmlRole { name: "_rts_name"; query: "retweeted_status/user/name/string()"; }
    XmlRole { name: "_rts_screen_name"; query: "retweeted_status/user/screen_name/string()"; }
    XmlRole { name: "_rts_text"; query: "retweeted_status/text/string()"; }
    XmlRole { name: "_rts_icon"; query: "retweeted_status/user/profile_image_url/string()";}
    XmlRole { name: "_rts_source"; query: "retweeted_status/source/string()"; }

    XmlRole { name: "_urls"; query: "entities/urls/string()"; }

    function clearData(){
        //カラデータを指定して無理やり消す
        //xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><statuses type=\"array\"><status><created_at /><id /><text /><source /><truncated /><favorited /><in_reply_to_status_id /><in_reply_to_user_id /><in_reply_to_screen_name /><retweet_count /><retweeted /><user><id /><name /><screen_name /><location /><description /><profile_image_url /><profile_image_url_https /><url /><protected /><followers_count /><profile_background_color /><profile_text_color /><profile_link_color /><profile_sidebar_fill_color /><profile_sidebar_border_color /><friends_count /><created_at /><favourites_count /><utc_offset /><time_zone /><profile_background_image_url /><profile_background_image_url_https /><profile_background_tile /><profile_use_background_image /><notifications /><geo_enabled /><verified /><following /><statuses_count /><lang /><contributors_enabled /><follow_request_sent /><listed_count /><show_all_inline_media /><default_profile /><default_profile_image /><is_translator /></user><geo /><coordinates /><place /><contributors /></status></statuses>";
        clear();
    }

    function makeQuery(){
        var ret = "/statuses/status";
        switch(sourceType){
        case 2:
            //DM
            ret = "/direct-messages/direct_message";
            queryParam1 = "sender";
            break;
        default:
            //timeline
            //mention
            //Lists
            //List
            //search list
            //search timeline
            //retweet by others(to me)
            //retweet by you(by me)
            //your tweets retweeted(of me)
            //favorites
            break;
        }

        return ret;
    }

    //最新のページを取得する
    function recent() {
        pageNumber = 0;
    }

    //次のページを取得する
    function more() {
        if (isReady) {
            pageNumber++;
//            console.debug("ModelXmlList:more: ready")
        }else{
//            console.debug("ModelXmlList:more: not ready")
        }
    }




    //最新を取得する
    function getRecent(){
        isAppendTop = true;
        makeTwitterUrl(1);
    }

    //次のページを取得する
    function getMore(){
        more();
        makeTwitterUrl(pageNumber);
    }


    //TwitterのURLを取得する
    function makeTwitterUrl(page_number){
        switch(sourceType){
        case 0:
            //timeline
            sourceTimeline = TwitterAPI.getTimelineURL(page_number);
            break;
        case 1:
            //mention
            sourceTimeline = TwitterAPI.getMentionURL(page_number);
            break;
        case 2:
            //DM
            sourceTimeline = TwitterAPI.getDirectMessageURL(page_number);
            break;
        case 3:
            //Lists
            break;
        case 4:
            //List
            if(listId.length === 0){
            }else{
                if(listId !== listIdPrev){
                    clear();
                    listIdPrev = listId;
                }
                sourceTimeline = TwitterAPI.getListStatusURL(listId, page_number);
            }
            break;
        case 5:
            //search list
            break;
        case 6:
            //search timeline
            break;
        case 7:
            //retweet by others(to me)
            sourceTimeline = TwitterAPI.getRetweetToMeURL(page_number);
            break;
        case 8:
            //retweet by you(by me)
            sourceTimeline = TwitterAPI.getRetweetByMeURL(page_number);
            break;
        case 9:
            //your tweets retweeted(of me)
            sourceTimeline = TwitterAPI.getRetweetOfMeURL(page_number);
            break;
        case 10:
            //favorites
            sourceTimeline = TwitterAPI.getFavoritesURL(page_number);
            break;
        case 11:
            //User Timeline
            Util.outputDebugString("user id=" + listId + ", last id=" + listIdPrev);
            if(listId.length === 0){
            }else{
                if(listId !== listIdPrev){
                    clearData();
                    listIdPrev = listId;
                }
                sourceTimeline = TwitterAPI.getUserTimelineURL(listId, page_number);
            }
            break;
        default:
            break;
        }
    }

    ///////////////////////////////////////////////
    //HTTPにアクセスし受信内容を確認します
    function requestHttp( method , url , on_func )
    {
        //XMLHttpRequestオブジェクト生成
        var httpoj = new XMLHttpRequest();
        //open メソッド
        httpoj.open( method , url , true );
        //受信時に起動するイベント
        httpoj.onreadystatechange = function(){
            //readyState値は4で受信完了
            if (httpoj.readyState==4){
                //コールバック
                if(on_func !== null){
                    on_func(httpoj.responseText);
                }
            }
        }
        //send メソッド
        httpoj.send( data );
    }


    //////////////////////////////////////////////////////
    //Timeline
    //ソースが変更されたらHTTPアクセスする
    onSourceTimelineChanged: {
//        Util.outputDebugString("ModelTimeline::onSourceTimelineChanged:\n" + sourceTimeline);
        if(!isReady){
            //処理中
            Util.outputDebugString("ModelTimeline::onSourceTimelineChanged: busy")
        }else if(sourceTimeline.length === 0){
            Util.outputDebugString("ModelTimeline::onSourceTimelineChanged: source lenght = 0")
        }else{
            Util.outputDebugString("ModelTimeline::onSourceTimelineChanged: start access")
            //Readyを落とす
            accessReady = false;
            //読込み開始
            var url = sourceTimeline;
            requestHttp("GET", url, onTimelineResponse);
        }
    }
    //Timelineアクセスの結果の応答
    function onTimelineResponse(responseText){
//        Util.outputDebugString("ModelTimeline::onTimelineResponse:");// + responseText);
        //読込み完了
        xml = responseText;
        //Readyにする
        accessReady = true;
    }


}
